package com.learnyou.server.xingzuo.dao.generator;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;
import org.ho.yaml.Yaml;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * <p>
 * mysql 代码生成器演示例子
 * </p>
 *
 * @author jobob
 * @since 2018-09-12
 */
public class MysqlGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * RUN THIS
     */
    public static void main(String[] args) throws FileNotFoundException {
        ConfigProperties properties = Yaml.loadType(MysqlGenerator.class.getResourceAsStream("/generator.yml"), ConfigProperties.class);
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/xingzuo-webserver-dao/src/main/java");
        gc.setAuthor(properties.getActiveDb().getAuthor());
        gc.setOpen(false);
        gc.setSwagger2(properties.getActiveDb().isSwagger());
        gc.setDateType(DateType.ONLY_DATE);
//        gc.setBaseResultMap(true);
        gc.setIdType(IdType.ASSIGN_ID);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(properties.getActiveDb().getUrl());
        dsc.setDbType(DbType.MYSQL);
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
//        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(properties.getActiveDb().getUsername());
        dsc.setPassword(properties.getActiveDb().getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
//        pc.setModuleName(scanner("模块名"));
//        pc.setModuleName("services");
        pc.setParent(properties.getActiveDb().getParentPackage());
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称
                return projectPath + "/xingzuo-webserver-dao/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null).disable(TemplateType.CONTROLLER));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.learnyou.server.xingzuo.dao.model.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setChainModel(true);
//        strategy.setSuperControllerClass("com.baomidou.mybatisplus.samples.generator.common.BaseController");
        strategy.setSuperEntityColumns("created_at","created_by","updated_at","updated_by","removed");
        strategy.setControllerMappingHyphenStyle(true);
        if (StringUtils.isNotEmpty(properties.getActiveDb().getTablePrefix())){
            strategy.setTablePrefix(StringUtils.split(properties.getActiveDb().getTablePrefix(), ","));
        }
        strategy.setCapitalMode(true);
        strategy.setLogicDeleteFieldName("removed");
        strategy.setEntityTableFieldAnnotationEnable(true);
//        String tables = scanner("表名");
        if (StringUtils.isNotEmpty(properties.getActiveDb().getIncludeTables())){
            strategy.setInclude(StringUtils.split(properties.getActiveDb().getIncludeTables(), ","));
        }
        mpg.setStrategy(strategy);
        // 选择 freemarker 引擎需要指定如下加，注意 pom 依赖必须有！
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

